import React from "react";
import { Helmet } from "react-helmet";
import { SearchBar, Tabs, Radio, List } from "antd-mobile";
const RadioItem = Radio.RadioItem;
const tabs = [
  { title: "全部" },
  { title: "写字楼" },
  { title: "小区" },
  { title: "商家" }
];
class Position extends React.Component {
  state = {
    value: "",
    checkValue: "",
    allDatas: [],
    officeBuildings: [],
    residentialAreas: [],
    markets: []
  };
  map = null;
  componentDidMount() {
    setTimeout(() => {
      document.getElementById("mapscript").onload = () => {
        this.map = new window.BMap.Map("map");
        var point = new window.BMap.Point(116.404, 39.915);
        this.map.centerAndZoom(point, 15);
        this.monitoring();
        var geolocation = new window.BMap.Geolocation();
        function getQueryString(name) {
          var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
          var r = window.location.search.substr(1).match(reg);
          if (r != null) {
              return unescape(r[2]);
          }
          return null;
      }
      var source = window.parent;
      console.log(navigator)
      navigator.geolocation.getCurrentPosition(function (position) {
        console.log("adasdasdas>...>oasjdalsdals")
          var success = {
              coords: {
                  speed: position.coords.speed,
                  latitude: position.coords.latitude,
                  longitude: position.coords.longitude,
                  altitude: position.coords.altitude,
                  accuracy: position.coords.accuracy,
                  altitudeAccuracy: position.coords. altitudeAccuracy,
                  heading: position.coords.heading
              },
              timestamp: position.timestamp,
              jsapiLoc: true
          }
          source.postMessage(JSON.stringify(success), '*');
      }, function (error) {
          var error = {
              code: error.code,
              message: error.message,
              jsapiLoc: true
          };
          source.postMessage(JSON.stringify(error), '*');
      }, {
          enableHighAccuracy: false,
          timeout: getQueryString('timeout'),
          maximumAge: getQueryString('maximumAge')
      });
        geolocation.getCurrentPosition(
          r => {
            if (this.getStatus() == window.BMAP_STATUS_SUCCESS) {
              var mk = new window.BMap.Marker(r.point);
              this.map.addOverlay(mk);
              this.map.panTo(r.point);
              alert("您的位置：" + r.point.lng + "," + r.point.lat);
            } else {
              // alert('failed'+this.getStatus());
            }
          },
          { enableHighAccuracy: true }
        );
      };
    }, 0);
  }

  monitoring() {
    // Firefox和Chrome早期版本中带有前缀
    var MutationObserver =
      window.MutationObserver ||
      window.WebKitMutationObserver ||
      window.MozMutationObserver;
    // 选择目标节点
    var target = document.querySelector("body");
    // 创建观察者对象
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        console.log(mutation.type);
        console.log(document.getElementsByTagName("iframe")[0].setAttribute("allow","geolocation"));
      });
    });
    // 配置观察选项:
    var config = { childList: true };
    // 传入目标节点和观察选项
    observer.observe(target, config);
    // 随后,你还可以停止观察
    //observer.disconnect();
  }
  /**
   * 地图区域搜索
   * @param {*} str
   */
  search = value => {
    console.log(value);
    var local = new window.BMap.LocalSearch(this.map, {
      renderOptions: { map: this.map },
      onSearchComplete: results => {
        console.log("result>>>>>>>>>>>>>>>>>>>");
        if (local.getStatus() === window.BMAP_STATUS_SUCCESS) {
          let s = [];
          for (let i = 0; i < results.getCurrentNumPois(); i++) {
            s.push({
              name: results.getPoi(i).title,
              address: results.getPoi(i).address
            });
          }
          console.log(s);
          switch (results.keyword) {
            case "写字楼":
              this.setState({
                officeBuildings: s
              });
              break;
            case "小区":
              this.setState({
                residentialAreas: s
              });
              break;
            case "商家":
              this.setState({
                markets: s
              });
              break;
            default:
              break;
          }

          console.log(results);
        }
      }
    });
    var localAll = new window.BMap.LocalSearch(this.map, {
      renderOptions: { map: this.map },
      onSearchComplete: results => {
        if (localAll.getStatus() === window.BMAP_STATUS_SUCCESS) {
          local.searchNearby("写字楼", this.map.getCenter(), 1000);
          local.searchNearby("小区", this.map.getCenter(), 1000);
          local.searchNearby("商家", this.map.getCenter(), 1000);
        }
      }
    });

    localAll.search(value);
  };

  onChange = value => {
    this.setState({ value: value });
  };
  checkChange = value => {
    this.setState({ checkValue: value });
  };
  cancel = () => {
    this.setState({ value: "" });
  };
  render() {
    const data2 = [
      { value: 0, label: "basketball", extra: "details" },
      { value: 1, label: "football", extra: "details" }
    ];
    const { value, checkValue } = this.state;
    return (
      <div>
        <Helmet>
          <script
            type="text/javascript"
            defer
            id="mapscript"
            src="http://api.map.baidu.com/getscript?v=3.0&ak=zZlVYw9mCu6i0xGuYs2iF0f785Fr7RhG&services=&t=20181212102423"
          />
        </Helmet>
        <SearchBar
          placeholder="请输入地点名称"
          value={this.state.value}
          onSubmit={value => this.search(value)}
          onCancel={this.cancel}
          onChange={this.onChange}
        />
        <div id="map" style={{ height: "50vh" }} />
        <Tabs tabs={tabs} initialPage={0} animated={false} useOnPan={false}>
          <List>
            {[
              ...this.state.officeBuildings,
              ...this.state.residentialAreas,
              ...this.state.markets
            ].map(i => (
              <RadioItem
                key={i.name + "all"}
                checked={checkValue === i.name}
                onChange={() => this.checkChange(i.name)}
              >
                {i.name}
                <List.Item.Brief>{i.address}</List.Item.Brief>
              </RadioItem>
            ))}
          </List>

          <List>
            {this.state.officeBuildings.map(i => (
              <RadioItem
                key={i.name}
                checked={checkValue === i.name}
                onChange={() => this.checkChange(i.name)}
              >
                {i.name}
                <List.Item.Brief>{i.address}</List.Item.Brief>
              </RadioItem>
            ))}
          </List>

          <List>
            {this.state.residentialAreas.map(i => (
              <RadioItem
                key={i.name}
                checked={checkValue === i.name}
                onChange={() => this.checkChange(i.name)}
              >
                {i.name}
                <List.Item.Brief>{i.address}</List.Item.Brief>
              </RadioItem>
            ))}
          </List>
          <List>
            {this.state.markets.map(i => (
              <RadioItem
                key={i.name}
                checked={checkValue === i.name}
                onChange={() => this.checkChange(i.name)}
              >
                {i.name}
                <List.Item.Brief>{i.address}</List.Item.Brief>
              </RadioItem>
            ))}
          </List>
        </Tabs>
        <style jsx="true">{`
          .am-tabs {
            height: calc(50vh - 44px);
            background-color: #fff;
          }
        `}</style>
      </div>
    );
  }
}

export default Position;
